package com.movie.controller;

import com.movie.dto.UserMovieStatsDTO;
import com.movie.entity.User;
import com.movie.service.OrderService;
import com.movie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户统计数据控制器
 */
@RestController
@RequestMapping("/api/users/stats")
public class UserStatsController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    /**
     * 获取当前用户的观影统计数据
     * @return 用户观影统计数据
     */
    @GetMapping("/movies")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<UserMovieStatsDTO> getUserMovieStats() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() ||
            "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).build();
        }

        // 从认证对象中获取用户ID
        Long userId = null;
        Object principal = authentication.getPrincipal();

        // 根据实际的用户详情对象类型获取用户ID
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            // 如果使用Spring Security的默认User对象，需要通过用户名查询用户ID
            String username = ((org.springframework.security.core.userdetails.User) principal).getUsername();
            // 通过用户服务查询用户ID
            User user = userService.findByUsername(username);
            if (user != null) {
                userId = user.getId();
            } else {
                return ResponseEntity.status(404).build();
            }
        } else if (principal instanceof com.movie.config.CustomUserDetails) {
            // 如果使用自定义的UserDetails实现
            userId = ((com.movie.config.CustomUserDetails) principal).getId();
        } else {
            return ResponseEntity.status(500).build();
        }

        // 获取用户观影统计数据
        UserMovieStatsDTO stats = orderService.getUserMovieStats(userId);
        return ResponseEntity.ok(stats);
    }
}
